<template>
  <div class="study-groups-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">学习小组</h1>
      <p class="page-subtitle">加入学习小组，共同备考，互相鼓励</p>
    </div>

    <!-- 小组广场 -->
    <template v-if="contentMode === 'discover'">
      <!-- 搜索和筛选 -->
      <div class="search-filter-section">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索学习小组"
            class="search-input"
            clearable
            suffix-icon="Search"
          />
        </div>

        <div class="filter-options">
          <div class="filter-group">
            <label>小组分类：</label>
            <el-select v-model="categoryFilter" placeholder="选择分类" clearable>
              <el-option label="全部" value="all"></el-option>
              <el-option label="行测学习" value="xingce"></el-option>
              <el-option label="申论学习" value="shenlun"></el-option>
              <el-option label="面试准备" value="mianshi"></el-option>
              <el-option label="综合学习" value="comprehensive"></el-option>
            </el-select>
          </div>

          <div class="filter-group">
            <label>排序方式：</label>
            <el-select v-model="sortBy" placeholder="选择排序" clearable>
              <el-option label="按成员数" value="members"></el-option>
              <el-option label="按创建时间" value="created"></el-option>
              <el-option label="按活跃度" value="active"></el-option>
            </el-select>
          </div>
        </div>
      </div>

      <!-- 小组列表 -->
      <div class="groups-list">
        <h2 class="section-title">热门小组</h2>
        <div class="groups-container">
          <GroupCard
            v-for="group in filteredGroups"
            :key="group.id"
            :group="group as any"
            :can-join="true"
            :show-stats="true"
            class="mb-4"
          />
        </div>
        
        <!-- 空状态 -->
        <div v-if="filteredGroups.length === 0" class="empty-state">
          <el-empty description="没有找到相关小组，请尝试其他关键词或筛选条件"></el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredGroups.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </template>

    <!-- 我的小组 -->
    <template v-else-if="contentMode === 'my'">
      <div class="section-title">
        <h2>我的小组</h2>
        <p>您已加入的学习小组</p>
      </div>
      
      <div class="my-groups-section">
        <div class="groups-container">
          <GroupCard
            v-for="group in myGroups"
            :key="group.id"
            :group="group as any"
            :can-join="false"
            :show-stats="true"
            :show-actions="true"
            class="mb-4"
          />
        </div>
        
        <!-- 空状态 -->
        <div v-if="myGroups.length === 0" class="empty-state">
          <el-empty description="您还没有加入任何小组，去发现页面加入吧！"></el-empty>
        </div>
      </div>
    </template>

    <!-- 创建小组 -->
    <template v-else-if="contentMode === 'create'">
      <div class="section-title">
        <h2>创建新小组</h2>
        <p>创建您自己的学习小组，邀请志同道合的伙伴</p>
      </div>
      
      <div class="create-group-section">
        <el-form :model="newGroupForm" label-width="100px">
          <el-form-item label="小组名称" prop="name">
            <el-input v-model="newGroupForm.name" placeholder="请输入小组名称" maxlength="50"></el-input>
          </el-form-item>
          <el-form-item label="小组分类" prop="category">
            <el-select v-model="newGroupForm.category" placeholder="选择小组分类">
              <el-option label="行测学习" value="xingce"></el-option>
              <el-option label="申论学习" value="shenlun"></el-option>
              <el-option label="面试准备" value="mianshi"></el-option>
              <el-option label="综合学习" value="comprehensive"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="小组描述" prop="description">
            <el-input v-model="newGroupForm.description" type="textarea" :rows="5" placeholder="请输入小组描述"></el-input>
          </el-form-item>
          <el-form-item label="标签" prop="tags">
            <el-input v-model="newGroupForm.tags" placeholder="请输入标签，用逗号分隔"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleCreateGroup">创建小组</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRoute } from 'vue-router';
import GroupCard from '@/components/GroupCard.vue';

const route = useRoute();

// 搜索关键词
const searchKeyword = ref('');

// 分类筛选
const categoryFilter = ref<string>('all');

// 排序方式
const sortBy = ref<string>('members');

// 创建小组表单数据
const newGroupForm = ref({
  name: '',
  description: '',
  category: '',
  tags: []
});

// 根据路由路径决定显示的内容类型
const contentMode = computed(() => {
  const path = route.path;
  console.log('当前路由路径:', path);
  if (path === '/study-groups/my') return 'my';
  if (path === '/study-groups/create') return 'create';
  if (path === '/study-groups') return 'discover';
  return 'discover';
});

// 我的小组数据
const myGroups = computed(() => {
  // 这里模拟获取当前用户加入的小组
  // 实际应用中应该根据用户ID从API获取
  return mockGroups.value.slice(0, 3);
});

// 处理创建小组
const handleCreateGroup = () => {
  // 这里应该有实际的创建小组逻辑
  console.log('创建小组:', newGroupForm.value);
  // 创建成功后重置表单
  newGroupForm.value = {
    name: '',
    description: '',
    category: '',
    tags: []
  };
  // 可以显示成功提示
};

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);

// 模拟学习小组数据
const mockGroups = ref([
  {
    id: 1,
    name: '行测专项突破',
    description: '专注于行测各模块的学习与训练，定期组织模拟考试和经验分享',
    type: 'study',
    coverImage: 'https://picsum.photos/id/3/300/200',
    memberCount: 1256,
    activityCount: 345,
    resourceCount: 89,
    latestActivity: {
      id: 1,
      title: '图形推理专项训练',
      startTime: new Date(Date.now() - 60 * 60 * 1000).toISOString()
    },
    members: [
      { id: 1, username: '组长', avatar: 'https://picsum.photos/id/1010/200/200', role: 'ADMIN' as const },
      { id: 2, username: '副组长', avatar: 'https://picsum.photos/id/1011/200/200', role: 'MODERATOR' as const },
      { id: 3, username: '组员1', avatar: 'https://picsum.photos/id/1012/200/200', role: 'MEMBER' as const },
      { id: 4, username: '组员2', avatar: 'https://picsum.photos/id/1013/200/200', role: 'MEMBER' as const },
      { id: 5, username: '组员3', avatar: 'https://picsum.photos/id/1014/200/200', role: 'MEMBER' as const }
    ],
    createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 2,
    name: '申论交流圈',
    description: '分享申论写作经验，互相批改作文，共同提高申论成绩',
    type: 'discussion',
    coverImage: 'https://picsum.photos/id/4/300/200',
    memberCount: 876,
    activityCount: 234,
    resourceCount: 67,
    latestActivity: {
      id: 2,
      title: '2024年国考申论预测',
      startTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
    },
    members: [
      { id: 6, username: '申论专家', avatar: 'https://picsum.photos/id/1015/200/200', role: 'ADMIN' as const },
      { id: 7, username: '写作爱好者', avatar: 'https://picsum.photos/id/1016/200/200', role: 'MODERATOR' as const },
      { id: 8, username: '学习者1', avatar: 'https://picsum.photos/id/1017/200/200', role: 'MEMBER' as const },
      { id: 9, username: '学习者2', avatar: 'https://picsum.photos/id/1018/200/200', role: 'MEMBER' as const },
      { id: 10, username: '学习者3', avatar: 'https://picsum.photos/id/1019/200/200', role: 'MEMBER' as const }
    ],
    createdAt: new Date(Date.now() - 45 * 24 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 3,
    name: '公考资料共享库',
    description: '免费分享各类公考学习资料，助力大家高效备考',
    type: 'resource_sharing',
    coverImage: 'https://picsum.photos/id/5/300/200',
    memberCount: 2156,
    activityCount: 178,
    resourceCount: 345,
    latestActivity: {
      id: 3,
      title: '2024年最新行测真题及解析',
      startTime: new Date(Date.now() - 5 * 60 * 60 * 1000).toISOString()
    },
    members: [
      { id: 11, username: '资料达人', avatar: 'https://picsum.photos/id/1020/200/200', role: 'ADMIN' as const },
      { id: 12, username: '共享者', avatar: 'https://picsum.photos/id/1021/200/200', role: 'MODERATOR' as const },
      { id: 13, username: '学习者A', avatar: 'https://picsum.photos/id/1022/200/200', role: 'MEMBER' as const },
      { id: 14, username: '学习者B', avatar: 'https://picsum.photos/id/1023/200/200', role: 'MEMBER' as const },
      { id: 15, username: '学习者C', avatar: 'https://picsum.photos/id/1024/200/200', role: 'MEMBER' as const }
    ],
    createdAt: new Date(Date.now() - 60 * 24 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 4,
    name: '国考冲刺班',
    description: '为备战2024年国考的同学提供高强度训练和指导',
    type: 'exam_prep',
    coverImage: 'https://picsum.photos/id/6/300/200',
    memberCount: 567,
    activityCount: 123,
    resourceCount: 45,
    latestActivity: {
      id: 4,
      title: '每日一练：行测套题训练',
      startTime: new Date(Date.now() - 12 * 60 * 60 * 1000).toISOString()
    },
    members: [
      { id: 16, username: '冲刺教练', avatar: 'https://picsum.photos/id/1025/200/200', role: 'ADMIN' as const },
      { id: 17, username: '助教', avatar: 'https://picsum.photos/id/1026/200/200', role: 'MODERATOR' as const },
      { id: 18, username: '学员1', avatar: 'https://picsum.photos/id/1027/200/200', role: 'MEMBER' as const },
      { id: 19, username: '学员2', avatar: 'https://picsum.photos/id/1028/200/200', role: 'MEMBER' as const },
      { id: 20, username: '学员3', avatar: 'https://picsum.photos/id/1029/200/200', role: 'MEMBER' as const }
    ],
    createdAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 5,
    name: '公基知识大杂烩',
    description: '涵盖公共基础知识各个领域，帮助考生全面备考',
    type: 'study',
    coverImage: 'https://picsum.photos/id/7/300/200',
    memberCount: 987,
    activityCount: 256,
    resourceCount: 123,
    latestActivity: {
      id: 5,
      title: '法律常识高频考点梳理',
      startTime: new Date(Date.now() - 3 * 60 * 60 * 1000).toISOString()
    },
    members: [
      { id: 21, username: '公基达人', avatar: 'https://picsum.photos/id/1030/200/200', role: 'owner' },
      { id: 22, username: '助教', avatar: 'https://picsum.photos/id/1031/200/200', role: 'manager' },
      { id: 23, username: '学员小明', avatar: 'https://picsum.photos/id/1032/200/200', role: 'member' },
      { id: 24, username: '学员小红', avatar: 'https://picsum.photos/id/1033/200/200', role: 'member' },
      { id: 25, username: '学员小李', avatar: 'https://picsum.photos/id/1034/200/200', role: 'member' }
    ],
    createdAt: new Date(Date.now() - 20 * 24 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 6,
    name: '面试经验交流群',
    description: '分享公务员面试经验，模拟面试场景，提高面试技巧',
    type: 'discussion',
    coverImage: 'https://picsum.photos/id/8/300/200',
    memberCount: 654,
    activityCount: 189,
    resourceCount: 56,
    latestActivity: {
      id: 6,
      title: '结构化面试答题技巧分享',
      startTime: new Date(Date.now() - 8 * 60 * 60 * 1000).toISOString()
    },
    members: [
      { id: 26, username: '面试专家', avatar: 'https://picsum.photos/id/1035/200/200', role: 'owner' },
      { id: 27, username: 'HR顾问', avatar: 'https://picsum.photos/id/1036/200/200', role: 'manager' },
      { id: 28, username: '考生小王', avatar: 'https://picsum.photos/id/1037/200/200', role: 'member' },
      { id: 29, username: '考生小张', avatar: 'https://picsum.photos/id/1038/200/200', role: 'member' },
      { id: 30, username: '考生小陈', avatar: 'https://picsum.photos/id/1039/200/200', role: 'member' }
    ],
    createdAt: new Date(Date.now() - 35 * 24 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 7,
    name: '省考备考联盟',
    description: '针对2024年各省公务员考试的备考交流平台',
    type: 'exam_prep',
    coverImage: 'https://picsum.photos/id/9/300/200',
    memberCount: 1890,
    activityCount: 321,
    resourceCount: 178,
    latestActivity: {
      id: 7,
      title: '2024年省考报名时间汇总',
      startTime: new Date(Date.now() - 4 * 60 * 60 * 1000).toISOString()
    },
    members: [
      { id: 31, username: '省考通', avatar: 'https://picsum.photos/id/1040/200/200', role: 'owner' },
      { id: 32, username: '备考顾问', avatar: 'https://picsum.photos/id/1041/200/200', role: 'manager' },
      { id: 33, username: '江苏考生', avatar: 'https://picsum.photos/id/1042/200/200', role: 'member' },
      { id: 34, username: '浙江考生', avatar: 'https://picsum.photos/id/1043/200/200', role: 'member' },
      { id: 35, username: '广东考生', avatar: 'https://picsum.photos/id/1044/200/200', role: 'member' }
    ],
    createdAt: new Date(Date.now() - 50 * 24 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 8,
    name: '行测错题本',
    description: '分享行测错题，分析错误原因，避免重复犯错',
    type: 'resource_sharing',
    coverImage: 'https://picsum.photos/id/10/300/200',
    memberCount: 765,
    activityCount: 145,
    resourceCount: 234,
    latestActivity: {
      id: 8,
      title: '图形推理易错题合集',
      startTime: new Date(Date.now() - 10 * 60 * 60 * 1000).toISOString()
    },
    members: [
      { id: 36, username: '错题整理师', avatar: 'https://picsum.photos/id/1045/200/200', role: 'owner' },
      { id: 37, username: '学习委员', avatar: 'https://picsum.photos/id/1046/200/200', role: 'manager' },
      { id: 38, username: '错题收集者', avatar: 'https://picsum.photos/id/1047/200/200', role: 'member' },
      { id: 39, username: '查漏补缺', avatar: 'https://picsum.photos/id/1048/200/200', role: 'member' },
      { id: 40, username: '学习到底', avatar: 'https://picsum.photos/id/1049/200/200', role: 'member' }
    ],
    createdAt: new Date(Date.now() - 25 * 24 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 9,
    name: '时政热点讨论组',
    description: '及时更新时政热点，分析考试重点，分享备考资料',
    type: 'discussion',
    coverImage: 'https://picsum.photos/id/11/300/200',
    memberCount: 1056,
    activityCount: 278,
    resourceCount: 98,
    latestActivity: {
      id: 9,
      title: '2024年两会热点解读',
      startTime: new Date(Date.now() - 1 * 60 * 60 * 1000).toISOString()
    },
    members: [
      { id: 41, username: '时政专家', avatar: 'https://picsum.photos/id/1050/200/200', role: 'owner' },
      { id: 42, username: '评论员', avatar: 'https://picsum.photos/id/1051/200/200', role: 'manager' },
      { id: 43, username: '时政迷', avatar: 'https://picsum.photos/id/1052/200/200', role: 'member' },
      { id: 44, username: '关注时事', avatar: 'https://picsum.photos/id/1053/200/200', role: 'member' },
      { id: 45, username: '新闻爱好者', avatar: 'https://picsum.photos/id/1054/200/200', role: 'member' }
    ],
    createdAt: new Date(Date.now() - 40 * 24 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 10,
    name: '选调生备考群',
    description: '为选调生考试提供专属备考指导和资料分享',
    type: 'study',
    coverImage: 'https://picsum.photos/id/12/300/200',
    memberCount: 456,
    activityCount: 112,
    resourceCount: 78,
    latestActivity: {
      id: 10,
      title: '选调生面试特点分析',
      startTime: new Date(Date.now() - 15 * 60 * 60 * 1000).toISOString()
    },
    members: [
      { id: 46, username: '选调生导师', avatar: 'https://picsum.photos/id/1055/200/200', role: 'owner' },
      { id: 47, username: '学长', avatar: 'https://picsum.photos/id/1056/200/200', role: 'manager' },
      { id: 48, username: '应届生A', avatar: 'https://picsum.photos/id/1057/200/200', role: 'member' },
      { id: 49, username: '应届生B', avatar: 'https://picsum.photos/id/1058/200/200', role: 'member' },
      { id: 50, username: '应届生C', avatar: 'https://picsum.photos/id/1059/200/200', role: 'member' }
    ],
    createdAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString()
  }
]);

// 根据搜索和筛选条件处理小组列表
const filteredGroups = computed(() => {
  let groups = [...mockGroups.value];
  
  // 根据关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    groups = groups.filter(group => 
      group.name.toLowerCase().includes(keyword) ||
      group.description.toLowerCase().includes(keyword)
    );
  }
  
  // 根据排序方式排序
  switch (sortBy.value) {
    case 'members_desc':
      groups.sort((a, b) => (b.memberCount || 0) - (a.memberCount || 0));
      break;
    case 'members_asc':
      groups.sort((a, b) => (a.memberCount || 0) - (b.memberCount || 0));
      break;
    case 'created_desc':
      groups.sort((a, b) => (new Date(b.createdAt || '').getTime() || 0) - (new Date(a.createdAt || '').getTime() || 0));
      break;
    case 'created_asc':
      groups.sort((a, b) => (new Date(a.createdAt || '').getTime() || 0) - (new Date(b.createdAt || '').getTime() || 0));
      break;
    default:
      break;
  }
  
  return groups;
});

// 分页大小变化处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
};

// 页码变化处理
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
};
</script>

<style lang="scss" scoped>
.study-groups-view {
  padding: 20px;
  padding-top: 100px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  .page-title {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 10px;
  }

  .page-subtitle {
    font-size: 1.2rem;
    opacity: 0.9;
  }
}

.action-section {
  margin-bottom: 30px;

  .search-filter-container {
    display: flex;
    gap: 15px;
    align-items: center;

    .search-input {
      flex: 1;
      max-width: 500px;
    }

    .filter-select {
      min-width: 150px;
    }

    .create-group-button {
      min-width: 120px;
    }
  }
}

.groups-section {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .groups-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e2e8f0;

    .groups-info {
      .groups-count {
        font-size: 16px;
        color: #666;
      }
    }

    .sort-options {
      .el-select {
        min-width: 150px;
      }
    }
  }

  .groups-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #e2e8f0;

    .el-pagination {
      .el-pager li {
        margin: 0 4px;
        min-width: 32px;
        height: 32px;
        line-height: 32px;
        font-size: 14px;
      }
    }
  }
}
</style>